package org.ccf.certified.business.shiro.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ccf.certified.business.shiro.model.Permission;
import org.ccf.certified.business.shiro.model.Role;
import org.ccf.certified.business.shiro.model.User;
import org.ccf.certified.business.shiro.repository.IPermissionRepository;
import org.ccf.certified.business.shiro.repository.IRoleRepository;
import org.ccf.certified.business.shiro.repository.IUserRepository;
import org.ccf.certified.exception.UnauthResourcesException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author LiuFang
 * @date 2022/1/12
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
public class UserManager extends ServiceImpl<IUserRepository, User> {


    @Autowired
    private IUserRepository userRepository;

    @Autowired
    private IRoleRepository roleRepository;

    @Autowired
    private IPermissionRepository permissionRepository;


    public User getUser(String username) {

        /** 根据用户名查询用户信息 */
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username",username);
        User user = userRepository.selectOne(wrapper);

        /** 没有此用户，直接返回null */
        if (user == null)
            return null;

        /**查询当前用户的角色和资源信息*/
        Set<Role> roles = roleRepository.findRolesByUserId(user.getId());
        /** 获取当前用户的角色集合ID */
        if(roles.isEmpty())
            throw new UnauthResourcesException("当前用户没有配置角色信息,请联系系统管理员进行配置,在进行访问...");

        /** 添加角色到用户信息 */
        user.setRoles(roles.stream().map(Role::getCode).collect(Collectors.toSet()));

        /** 查询角色所包含的资源配置信息 */
        Set<Long> roleSet = roles.stream().map(Role::getId).collect(Collectors.toSet());
        Set<Permission> permissions = permissionRepository.findPermissionsByRoleId(roleSet);

        if(permissions.isEmpty())
            throw new UnauthResourcesException("当前用户没有可以访问的资源信息,请联系系统管理员进行配置,在进行访问...");

        /** 添加资源列表到用户信息 */
        user.setPermission(permissions.stream().map(Permission::getCode).collect(Collectors.toSet()));

        return user;
    }
}
